package com.ibeetl.cms.web;

import com.ibeetl.admin.console.service.RoleConsoleService;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreRole;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileItem;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.DateUtil;
import com.ibeetl.admin.core.util.PlatformException;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.ComprehensiveQuery;
import com.ibeetl.cms.service.BusinessProcessService;
import com.ibeetl.cms.service.ComprehensiveQueryService;
import com.ibeetl.cms.util.ProcessConstant;
import com.ibeetl.cms.util.RoleConstant;
import com.ibeetl.cms.web.quer3.ComprehensiveQuery3;
import com.ibeetl.cms.web.query.ComprehensiveQueryQuery;
import com.ibeetl.cms.web.query2.ComprehensiveQueryQuery2;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

/**
 * ComprehensiveQuery 接口
 */
@Controller
public class ComprehensiveQueryController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/comprehensiveQuery";


    @Autowired
    private ComprehensiveQueryService comprehensiveQueryService;

    @Autowired
    CorePlatformService platformService;

    @Autowired
    RoleConsoleService roleConsoleService;


    @Autowired
    FileService fileService;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("comprehensiveQuery")
    @ResponseBody
    public ModelAndView index() {
        CoreUser currentUser = platformService.getCurrentUser();
        Long roleName=Long.parseLong(roleConsoleService.getRoleName(currentUser.getId().intValue()));
        ModelAndView view = new ModelAndView("/cms/comprehensiveQuery/index.html") ;
        //根据不同的用户，不一样的搜索项目
        if(roleName.equals(RoleConstant.HUMAN_SOCIETY)){
            view.addObject("search", ComprehensiveQueryQuery2.class.getName());
        }else if(roleName.equals(RoleConstant.COMPANY)){
            view.addObject("search", ComprehensiveQuery3.class.getName());
        }else{
            view.addObject("search", ComprehensiveQueryQuery.class.getName());
        }
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("cms.comprehensiveQuery.edit")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/comprehensiveQuery/edit.html");
        ComprehensiveQuery comprehensiveQuery = comprehensiveQueryService.queryById(id);
        view.addObject("comprehensiveQuery", comprehensiveQuery);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("cms.comprehensiveQuery.add")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/comprehensiveQuery/add.html");
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("comprehensiveQuery")
    @ResponseBody
    public JsonResult<PageQuery> list(ComprehensiveQueryQuery condition)
    {
        /**
         * 不一样的用户，显示不一样的内容
         * 个人只能看到自己的，企业看到本企业的，初审，复审看到所有的
         */
        CoreRole role = platformService.getRole();
        CoreUser user = platformService.getCurrentUser();
        if(role.getId() == RoleConstant.PERSON){
           // condition.setUserId(user.getId().toString());
            condition.setIdentificationNumber(user.getCode());
        }else if(role.getId() == RoleConstant.COMPANY){
            condition.setCompanyId(user.getId().toString());
            condition.setSocialCreditCode(user.getId().toString());
        }else{

        }
        PageQuery page = condition.getPageQuery();
        comprehensiveQueryService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/add.json")
    @Function("cms.comprehensiveQuery.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)ComprehensiveQuery comprehensiveQuery)
    {
        comprehensiveQueryService.save(comprehensiveQuery);
        return new JsonResult().success();
    }

    @PostMapping(MODEL + "/update.json")
    @Function("cms.comprehensiveQuery.update")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  ComprehensiveQuery comprehensiveQuery) {
        boolean success = comprehensiveQueryService.updateTemplate(comprehensiveQuery);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


   
    @GetMapping(MODEL + "/view.json")
    @Function("cms.comprehensiveQuery.query")
    @ResponseBody
    public JsonResult<ComprehensiveQuery>queryInfo(Integer id) {
        ComprehensiveQuery comprehensiveQuery = comprehensiveQueryService.queryById( id);
        return  JsonResult.success(comprehensiveQuery);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("cms.comprehensiveQuery.delete")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        comprehensiveQueryService.batchDelComprehensiveQuery(idList);
        return new JsonResult().success();
    }
    
    
    @PostMapping(MODEL + "/excel/export.json")
    @Function("cms.comprehensiveQuery.export")
    @ResponseBody
    public JsonResult<String> export(HttpServletResponse response,ComprehensiveQueryQuery condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此comprehensiveQueryService.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/cms/comprehensiveQuery/你的excel模板文件名字.xls";
        PageQuery<ComprehensiveQuery> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<ComprehensiveQuery> list =comprehensiveQueryService.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("ComprehensiveQuery_"+DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
        
    }
    
    @PostMapping(MODEL + "/excel/import.do")
    @Function("cms.comprehensiveQuery.import")
    @ResponseBody
    public JsonResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
           return JsonResult.fail();
        }
        InputStream ins = file.getInputStream();
        /*解析模板并导入到数据库里,参考DictConsoleContorller，使用jxls reader读取excel数据*/
        ins.close();
        return JsonResult.success();
    }

    @Autowired
    private BusinessProcessService businessProcessService;

    /**
     ** 功能描述: 业务强制退回初始状态
     ** @author liujun
     ** @date 2019/5/14 16:58
     **/
    @PostMapping(MODEL + "/blakInitStatus.do")
    @Function("cms.comprehensiveQuery.updateStatusById")
    @ResponseBody
    public JsonResult<String> updateStatusById(String businessType,Integer businessId) {
        try {
            if(null == businessId || StringUtils.isBlank(businessType)){
                return JsonResult.failMessage("提交数据不完整，操作失败!");
            }
            String tableName = getBusinessTableName(businessType);
            if(StringUtils.isBlank(tableName)){
                return JsonResult.failMessage("该业务类型不支持强制回退操作!");
            }
            comprehensiveQueryService.updateStatusById(tableName,businessId);
            //调用增加业务流程数据
            businessProcessService.processInformation(businessId, ProcessConstant.DONE_STR,
                    ProcessConstant.DONE,"人社管理员-业务状态强制退回初始状态","操作成功"
                    , businessType);
            return new JsonResult().success();
        } catch (Exception e) {
            log.error(e);
            e.printStackTrace();
        }
        return JsonResult.failMessage("操作失败，请重新登陆系统确认操作结果。");
    }

    public String getBusinessTableName(String businessType){
        if (businessType.equals("1")) {
            return "industrial_talents";
        } else if (businessType.equals("3")) {
            return "buy_house_subsidies";
        } else if (businessType.equals("4")) {
            return "skill";
        } else if (businessType.equals("5")) {
            return "professional_technology";
        } else if (businessType.equals("6")) {
            return "renting";
        } else if (businessType.equals("7")) {
            return "doctoral_subsidy";
        } else if (businessType.equals("8")) {
            return "outbound_subsidy";
        } else if (businessType.equals("9")) {
            return "highlevel_talents";
        } else if (businessType.equals("13")) {
            return "key_information";
        } else if (businessType.equals("14")) {
            return "medical_care";
        } else if (businessType.equals("15")) {
            return "insurance";
        }
        return "";
    }
}
